package com.cyl.wms.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.wms.domain.MaterialItemType;
import com.cyl.wms.mapper.MaterialItemTypeMapper;
import com.cyl.wms.pojo.query.MaterialItemTypeQuery;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialItemTypeService {
    @Autowired
    private MaterialItemTypeMapper materialItemTypeMapper;
    public List<MaterialItemType> selectList(MaterialItemTypeQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<MaterialItemType> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        return materialItemTypeMapper.selectList(qw);
    }

    /**
     * 获取全部数据
     * @param query 物料
     * @return 结果
     *
     * */
    public List<MaterialItemType> selectListAll(MaterialItemTypeQuery query) {
        QueryWrapper<MaterialItemType> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        Long itemTypeId = query.getItemTypeId();
        if (itemTypeId != null) {
            qw.eq("id", itemTypeId);
        }
        return materialItemTypeMapper.selectList(qw);
    }

    /**
     * 新增物料类型
     *
     * @param MaterialItemType 物料
     * @return 结果
     */
    public int insert(MaterialItemType MaterialItemType) {
        return materialItemTypeMapper.insert(MaterialItemType);
    }

    /**
     * 批量删除货区
     *
     * @param ids 需要删除的货区主键
     * @return 结果
     */
    public int deleteByIds(String ids) {
        QueryWrapper<MaterialItemType> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        qw.eq("id", ids);
        List item =  materialItemTypeMapper.selectList(qw);
        if(item.isEmpty()) {
            return materialItemTypeMapper.deleteById(ids);
        } else {
            // 如果List不为空的逻辑处理
            for (Object materialItemType : item) {
                if (materialItemType instanceof MaterialItemType) {
                    MaterialItemType items = (MaterialItemType) materialItemType;
                    System.out.println("getId:" + items.getId());
                    QueryWrapper<MaterialItemType> qws = new QueryWrapper<>();
                    qws.eq("del_flag",0);
                    qws.eq("parent_id", items.getId());
                    List list =  materialItemTypeMapper.selectList(qws);
                    if(list.isEmpty()){
                        return materialItemTypeMapper.deleteById(ids);
                    }else {
                        return 2;
                    }
                }
            }
        }
        return 2;
    }
}
